package com.ehsy.util;


import com.alibaba.fastjson2.JSON;

import java.util.List;

/**
 * @author YanZhen_Li
 * @version 1.0
 * @title JsonFormatUtils
 * @description
 * @create 2024/6/15 17:57
 */
public class JsonFormatUtils {
    public static <T> T toObjectByUnderline(String json, Class<T> clazz){
        String finalJsonStr = underlineReplace(json);
        return JSON.parseObject(finalJsonStr, clazz);
    }

    public static <T> List<T> toArrayByUnderline(String json, Class<T> clazz){
        String finalJsonStr = underlineReplace(json);
        return JSON.parseArray(finalJsonStr, clazz);
    }

    private static String underlineReplace(String json){
        String s = json.replaceAll("(_)([a-zA-Z])", "$1\uFFFF$2");
        // 第二步：处理标记，转换并移除
        StringBuilder result = new StringBuilder(s);
        int index;
        while ((index = result.indexOf("\uFFFF")) != -1) {
            char nextChar = result.charAt(index + 1);
            if (Character.isLetter(nextChar)) {
                result.setCharAt(index, Character.toUpperCase(nextChar));
                result.deleteCharAt(index + 1);
                result.deleteCharAt(index - 1);
            } else {
                result.deleteCharAt(index);
                result.deleteCharAt(index-1);
            }
        }
        return result.toString();
    }
}
